<template>

<!--        下拉框选择分类 1 2 3 级   品牌下拉框-->
  <div style="margin: 20px">


    <div>
      <el-form :inline="true"  class="demo-form-inline">
        <el-form-item label="分类">
          <el-cascader v-model="categories" :props="props"/>

        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="queryParams.brandId"  placeholder="请选择" style="width: 200px">
            <el-option
                v-for="brand in brands"
                :key="brand.id"
                :label="brand.name"
                :value="brand.id"
            />
          </el-select>
        </el-form-item>

<!--        ======================模糊 搜索  重置======================-->
       <el-form-item>
         <el-button type="primary" icon="Search" @click="initData">搜索</el-button>
         <el-button icon="Refresh" @click="handleReset">重置</el-button>
       </el-form-item>
      </el-form>

    </div>
    <div>
      <!--   新增 修改  删除-->
      <div>
<!--        点击新增按钮 弹出对话框 -->
        <el-button type="primary" icon="Plus" @click="dialogVisible=true;tips='添加分类品牌';handleReset()" plain>新增</el-button>
        <el-button type="success" icon="Edit"  plain>修改</el-button>
        <el-button type="danger" icon="Delete" @click="handleBacheDel" plain>删除</el-button>
      </div>
    </div>
    <!--      表格      -->
    <div style="margin-top: 10px;margin-bottom: 20px">
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column  type="selection" width="55" >
        </el-table-column>
        <el-table-column label="分类名称" prop="categoryName" width="120">
        </el-table-column>
        <el-table-column label="品牌名称" prop="brandName" width="120">
        </el-table-column>
        <el-table-column  label="品牌图标"  >
          <template #default="scope">
            <el-image style="width: 50px; height: 50px" :src="scope.row.logo" :fit="fit" />
          </template>
        </el-table-column>

        <el-table-column property="createTime" label="创建时间"  />
        <el-table-column property="opreation" label="操作"  >
          <template #default="scope">
            <!--        修改 和 删除 按钮    -->
            <el-button icon="Edit" link type="primary" size="small"  @click="handleShowEditDialog(scope.row.id)">
              修改
            </el-button>
            <el-button icon="Delete" link type="danger" size="small"  @click="handleDelete(scope.row)">
              删除
            </el-button>

          </template>

        </el-table-column>

      </el-table>


    </div>
<!--    =========================================分页查询===================================================-->
    <div class="demo-pagination-block" style="margin-left: 950">

      <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[1, 2, 3, 4,10]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="initData"
          @current-change="initData"
      />
    </div>
    <!--  =========================================== 修改和新增的对话框=====================================-->
    <el-dialog
        v-model="dialogVisible"
        :title="tips"
        width="500"
    >
      <el-form  ref="dialogFormRef"  :rules="rules" :model="categoryBrand"  >
      <el-form-item label="分类" prop="categoryId">
        <el-cascader v-model="categories" :props="props"/>
      </el-form-item>
        <el-form-item label="品牌"  prop="brandId">
            <el-select v-model="categoryBrand.brandId"  placeholder="请选择" style="width: 200px">
            <el-option
                v-for="brand in brands"
                :key="brand.id"
                :label="brand.name"
                :value="brand.id"
            />
          </el-select>
        </el-form-item>

      <!--     单机事件 点击确定之后 发起触发方法 确定 即发起修改请求  取消更改dialogVisible-->

      </el-form>
      <template #footer>
        <div >
          <el-button @click="dialogVisible = false;handleReset()">
            取消
          </el-button>
          <el-button type="primary" @click="handleSaveOrUpdate;dialogVisible=false;handleReset()">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>



  </div>





</template>

<script setup>
import {listAllBrand,listBrand,getbrand,addbrand,updatebrand,delbrand} from "@/api/product/brand.js"
import {ElMessage, ElMessageBox} from "element-plus";
import { getToken } from "@/utils/auth";
import{listcategory} from "@/api/product/category.js"
import {
  listCategoryBrand,
  addCategoryBrand,
  updateCategoryBrand,
  getCategoryBrand,
  delCategoryBrand
} from "@/api/product/categoryBrand.js"


onMounted(async ()=>{

 const {data} =await listAllBrand()
  brands.value = data
  initData()
})







let dialogVisible =ref(false);
// 搜索表单：级联选择器需要的属性
//   分类级联选择器：数据绑定
const categories = ref(null)

const tableData =ref([])
const queryParams = ref({
  pageNum: 1,
  pageSize: 3,
  //品牌查询条件
  brandId: null,
  //按分类查询的条件
  categoryId:null
})
const brands = ref([])
const total = ref(100)
const initData =async ()=>{
  if (categories.value && categories.value.length==3 ){
      queryParams.value.categoryId = categories.value[2]
  }

  const {rows,total:t} =  await listCategoryBrand(queryParams.value)
  total.value=t
  tableData.value = rows;
  console.log(tableData.value)
}

//  分类级联选择器配置
const props = {
  lazy: true, //开启懒加载
  label: 'name',//配置级联选择器使用数据的哪个属性值当作标题  默认使用label属性
  value: 'id', //配置级联选择器 节点选中后的哪个属性值 被接收  默认value
  //node：表示点击的节点 ， resolve：可以将加载的数据渲染到点击的节点的下一级
  async lazyLoad(node, resolve) { //懒加载回调：默认点击一个节点时，触发加载他的下一级节点
    //根据node节点的 id当作父id加载下一级节点
    const id = +node.level===0?0:node.data.id
    //先加载一级分类列表展示
    const {data} = await listcategory(id)

    data.forEach(categorie=>{
      categorie.leaf = !categorie.hasChildren
    })
    resolve(data)

  },
}

//重置方法

const handleReset = ()=>{
  queryParams.value={
    pageNum: 1,
    pageSize: 3,
    //品牌查询条件
    brandId: null,
    //按分类查询的条件

    categoryId:null
  }
  categoryBrand.value.brandId=null
  categories.value=null
  initData()
}
//



//对话框标题
const tips = ref("添加分类品牌")




//新增/更新对话框 表单校验
const rules = ref({
  categoryId: [
    {required: true, message: '请选择三级分类', trigger: 'blur'}
  ],
  brandId: [
    {required: true, message: '请选择品牌', trigger: 'blur'}
  ],
})
//对话框中分类品牌的属性
const categoryBrand = ref({
  name: '',
  logo: null
})
//接收form表单数据
const dialogFormRef = ref()
const handleSaveOrUpdate =async ()=>{
  //1、校验表单收集的数据之前，需要将选择的三级分类 三级id设置给表单绑定的对象指定属性
  if(categories.value && categories.value.length === 3){
    categoryBrand.value.categoryId = categories.value[2]
  }
  dialogFormRef.value.validate((validate)=>{
    if(validate){
      //3、校验通过  提交新增 或 更新请求
      console.log(categories.value.length)
      console.log(categories.value)
      console.log(categoryBrand.value)
      if(!categories.value || categories.value.length !=3 || !categoryBrand.value.brandId){
        ElMessage.warning('请完善分类品牌的数据')
        return
      }
      if (categoryBrand.value.id) {
        //更新
         handleUpdate()

      } else {
        //新增
         handleSave()


      }
      handleReset()
      initData()
    }else{
      //校验失败
      ElMessage.warning('数据校验失败')
    }
  })


}

//修改更新分类品牌
const handleUpdate =async ()=>{

  await updateCategoryBrand(categoryBrand.value)
  categories.value=null

  initData()
  ElMessage("修改成功")
}

//新增分类品牌
const handleSave =async () => {

        await addCategoryBrand(categoryBrand.value)
  ElMessage("添加分类品牌成功")

}
//点击修改按钮 更改状态  回显数据
const handleShowEditDialog =async (row)=>{
  console.log(row)
  const {data} = await getCategoryBrand(row)
  categories.value = data.categoryIdList
  console.log(categories.value)
  //使用新增/更新 对话框 表单绑定的brand接收查询到的数据 回显
  categoryBrand.value = data
  tips.value = '修改分类品牌'
  categoryBrand.value.id = row
  dialogVisible.value = true
}


//单行删除
const handleDelete = (row)=>{
  console.log(row.id)
  ElMessageBox.confirm(
      "是否删除",{
        confirmButtonText :'删除',
        cancelButtonText:'取消删除'
      }
  ).then(
      async ()=>{
        await delCategoryBrand(row.id)
        initData()

      }
  ).catch(
      (e)=>{
        ElMessage("取消删除")
      }
  )
}


const selectionCategoryBrands = ref([])
//复选框的函数
const handleSelectionChange = (row)=>{
  selectionCategoryBrands.value = row
}
//复选框勾选 批量删除

const handleBacheDel = ()=>{
  let selectIds = selectionCategoryBrands.value.map((item) => item.id).join(); //1,2,3
  if (!selectionCategoryBrands.value ||selectionCategoryBrands.value.length ===0 ){
    ElMessage.warning("未选择需要删除的品牌")
    return
  }else {
/*    debugger
    console.log(selectIds)
    return;*/
    console.log(selectIds)
    ElMessageBox.confirm("是否删除",{
      confirmButtonText:'确定删除',
      cancelButtonText:'取消删除'
    }).then(async ()=>{

      await delCategoryBrand(selectIds)
      ElMessage("删除成功")
      initData()
    }).catch(
        (e)=>{
          ElMessage("取消删除")
        }
    )

  }


}



</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>

<style >

</style>